//
//  XMUserCreateViewController.m
//  XiaoMiao
//
//  Created by Jim huang on 2018/4/25.
//  Copyright © 2018年 smallyou. All rights reserved.
//


//controller
#import "XMUserCreateViewController.h"
#import "AddressProvinceCityController.h"
#import "XMCameraTimeAndAngleViewController.h"
#import "XMUserDetailInfoViewController.h"
#import "XMAlbumController.h"
#import "SuccessToOriginController.h"


//view
#import "BRStringPickerView.h"
#import "XMUserExistAlterView.h"


//model

//request

//other
#import "LocationManager.h"


@interface XMUserCreateViewController ()<UITextViewDelegate,UITextFieldDelegate>

//下一步
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

//姓名
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
//性别
@property (weak, nonatomic) IBOutlet UIView *sexView;
@property (weak, nonatomic) IBOutlet UITextField *sexTextField;
//所在地
@property (weak, nonatomic) IBOutlet UIView *cityView;
@property (weak, nonatomic) IBOutlet UITextField *cityTextField;

//详细地址
@property (weak, nonatomic) IBOutlet UITextView *detailAddressTextView;
@property (weak, nonatomic) IBOutlet UILabel *detailAddressPlaceHolder;
//选填资料
@property (weak, nonatomic) IBOutlet UIView *detailInfoView;

@property (assign, nonatomic) BOOL  isCheckName;
//省份
@property (nonatomic,copy) NSString *province;
//城市
@property (nonatomic,copy) NSString *city;

//城市
@property (nonatomic,assign) BOOL userWasCreate;
@end

@implementation XMUserCreateViewController

+(instancetype)userCreateView{
    
    return [[[NSBundle mainBundle] loadNibNamed:@"XMUserCreateViewController" owner:nil options:nil] lastObject];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBgColor;
    self.title = @"填写资料";
    
    self.detailAddressTextView.delegate = self;
    self.nameTextField.delegate = self;
    //设置点击事件
    NSArray *tapViews = @[self.sexView, self.cityView, self.detailInfoView];
    for (UIView *tapView in tapViews) {
        [tapView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapViewDidTap:)]];
    }
    
    //设置button事件
    [self.nextBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //获取默认位置
    WEAKSELF
    [[LocationManager manager] startLocationLocationBlock:^(NSString *province, NSString *city) {
        weakSelf.cityTextField.text = [NSString stringWithFormat:@"%@ %@", province, city];
        weakSelf.province = province;
        weakSelf.city = city;
    }];
    [self.nameTextField becomeFirstResponder];

}

#pragma mark -netWork
-(void)checkUserRealyName{

    if (self.nameTextField.text.length == 0) {
        self.isCheckName = NO;
        [KLProgressHUD showErrorHUDWithMessage:@"请填写客户真实姓名"];
        return;
    }
    
    [KLProgressHUD showWaitingHUD];
    

    MJWeakSelf
    [AppNetwork album_CheckUserNameWithrealName:self.nameTextField.text completion:^(BOOL success,NSString * partyId ,NSString *errorMsg) {

        [KLProgressHUD hideHUDWithAnimated:YES];
        if (!success) {
            weakSelf.userWasCreate = NO;
            MJWeakSelf
            [XMUserExistAlterView showExistAlterViewWithresultBlock:^(NSInteger selectNum) {
                if (selectNum == 1) {
                    [KLProgressHUD showErrorHUDWithMessage:@"提示：该用户已存在,请修改姓名或添加后缀标识"];
                    [weakSelf.nameTextField becomeFirstResponder];
                    weakSelf.createModel.partyId = @"";
                }else if (selectNum == 2){
                    
                    weakSelf.createModel.partyId = @"";

                    XMAlbumController * albumVC = [[XMAlbumController alloc]init];
                    albumVC.partyId = partyId;
                    
                    [albumVC setDismissCallBlock:^{
                        [weakSelf.nameTextField becomeFirstResponder];
                    }];
                    [weakSelf.navigationController pushViewController:albumVC animated:YES];
                    
                }else if (selectNum == 3){
                    weakSelf.createModel.partyId = partyId;
                    weakSelf.userWasCreate = YES;
                    [weakSelf btnDidClick:weakSelf.nextBtn];
                }
            }];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                weakSelf.isCheckName = NO;
            });
            

            
        }else{
            

            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                weakSelf.isCheckName = NO;
            });
        }

    }];
    
}


#pragma mark - Action
//cell 点击
- (void)tapViewDidTap:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
    UIView *tapView = tap.view;
    
    if (self.isCheckName) {
        return;
    }
    
    if (tapView == self.sexView) {
        [self p_showSexPicker];
    }else if (tapView == self.cityView) {
        [self p_showLocationList];
    }else if (tapView == self.detailInfoView){
        
        XMUserDetailInfoViewController * vc = [[XMUserDetailInfoViewController alloc]init];
        vc.createModel = self.createModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


//确定完成
- (void)btnDidClick:(UIButton *)sender {
    if (sender != self.nextBtn) {
        return;
    }
    
    if (self.isCheckName) {
        return;
    }
    
    if (self.nameTextField.text.length == 0) {
        [KLProgressHUD showErrorHUDWithMessage:@"请填写客户真实姓名"];
        return;
    }
    
    if (!self.userWasCreate) {
        if (self.sexTextField.text.length == 0) {
            [KLProgressHUD showErrorHUDWithMessage:@"请选择客户性别"];
            return;
        }
        
    }

    
    self.createModel.realName = self.nameTextField.text;
    self.createModel.sex = self.sexTextField.text;
    self.createModel.province = self.province;
    self.createModel.city = self.city;
    self.createModel.addr = self.detailAddressTextView.text;
    
    [KLProgressHUD showWaitingHUD];
    MJWeakSelf
    [AppNetwork album_createUserDataWithModel:self.createModel completion:^(BOOL success, NSString *data, AppError *error) {
        [KLProgressHUD hideHUDWithAnimated:YES];
        if (success) {
            
            SuccessToOriginController *success = [[SuccessToOriginController alloc] init];
            [success setNavTitle:@"新建完成" desTitle:@"新建完成" btnTitle:@"返回查询"];
            [weakSelf.navigationController pushViewController:success animated:YES];
            
            [success setBtnClickHandle:^(SuccessToOriginController *btnVC) {
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }];
        }else{
            [KLProgressHUD showErrorHUDWithMessage:[error errorMessage]];
        }
    }];
    
    // 请求参数
//    NSString *msg = [self p_valiteIsCanCreatUser];
//    if (msg.length != 0) {
//        [self.view endEditing:YES];
//        [KLProgressHUD showPromptHUDWithMessage:msg];
//        return;
//    }
//
//
//    NSArray *locationArray = [self.cityTextField.text componentsSeparatedByString:@" "];
//    NSString *province = nil;
//    NSString *city = nil;
//    if (locationArray.count == 2) {
//        province = locationArray[0];
//        city = locationArray[1];
//    }
    
//    BaseInfoModel *infoModel =
//    [BaseInfoModel modelWithProfile:self.imageServerPath
//                           realName:self.nameTextField.text
//                                sex:self.sexTextField.text
//                                age:age
//                               prix:@"86"
//                              phone:self.phoneTextField.text
//                           province:province
//                               city:city];

    //    }
}


//展示性别
- (void)p_showSexPicker {
    WEAKSELF
    [BRStringPickerView showStringPickerWithTitle:nil dataSource:kSexArray defaultSelValue:self.sexTextField.text resultBlock:^(id selectValue) {
        
        if ([NSString app_isBlankString:weakSelf.sexTextField.text] && [NSString app_isBlankString:selectValue]) {
            weakSelf.sexTextField.text = kSexArray[0];
        }else {
            weakSelf.sexTextField.text = selectValue;
        }
    }];
}

//选择地区
- (void)p_showLocationList {
    AddressProvinceCityController *address = [[AddressProvinceCityController alloc] initWithAddressVCType:AddressVCTypeProvince parentId:@"" titleName:@""];
    [self.navigationController pushViewController:address animated:YES];
    
    WEAKSELF
    [address setAddressCompleted:^(NSString *province, NSString *city) {
        weakSelf.cityTextField.text = [NSString stringWithFormat:@"%@ %@", province, city];
        weakSelf.province = province;
        weakSelf.city = city;
    }];
}


#pragma mark - textviewDelegate
-(void)textViewDidChange:(UITextView *)textView{
    self.detailAddressPlaceHolder.hidden = textView.text.length;
}





#pragma mark -textFieldDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == self.nameTextField) {
        self.isCheckName = YES;
        [self checkUserRealyName];
    }
}


#pragma mark - Private
- (NSString *)p_valiteIsCanCreatUser {

    if ([NSString app_isBlankString:self.nameTextField.text]) {
        return @"请输入姓名";
    }

    if ([NSString app_isBlankString:self.sexTextField.text]) {
        return @"请选择性别";
    }

    
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
